package ils.domain.acquisition.model;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderFactoryImpl implements OrderFactory
{
    private SessionFactory sessionFactory;
    private static final String GET_ORDERS_OPEN = "select order from Order as order where order.status = 'open' order by order.orderDate desc";
    private static final Logger logger = LoggerFactory.getLogger(OrderFactoryImpl.class);
    private static final String GET_ITEMS = "select item from OrderItem as item where item.id in (:idList)";
    @Override
    public void createOrder(Order order)
    {
        if(order.getOrderDate() == null) order.setOrderDate(new Date());
        logger.debug("order details: " + order + ", item details: " + order.getItems());
        Session session = sessionFactory.getCurrentSession();
        session.save("ils.domain.acquisition.model.Order", order);
    }
    @Override
    public Order getOrder(int id)
    {
        Session session = sessionFactory.getCurrentSession();
        return (Order)session.load(Order.class, id);
    }
    @Override
    public void updateOrder(Order order)
    {
        Session session = sessionFactory.getCurrentSession();
        session.save("ils.domain.acquisition.model.Order", order);
    }
    public void setSessionFactory(SessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
    }
    @SuppressWarnings("unchecked")
    @Override
    public List<Order> getOpenOrders()
    {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery(GET_ORDERS_OPEN);
        return query.list();
    }
    @SuppressWarnings("unchecked")
    @Override
    public Map<Integer, OrderItem> getItems(List<Integer> itemIds)
    {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery(GET_ITEMS);
        query.setParameterList("idList", itemIds);
        List<OrderItem> items = query.list();
        Map<Integer, OrderItem> itemMap = new HashMap<Integer, OrderItem>();
        for(OrderItem item : items)
        {
            itemMap.put(item.getId(), item);
        }
        return itemMap;
    }
    
}
